package com.lyx.utils;

import com.lyx.entity.Menu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName MenuTreeBuilder
 * @Description: TODO
 * @Author 86152
 * @Date 2022/3/3
 * @Version V1.0
 **/
public class MenuTreeBuilder {
    /**
     * */
    public static List<Menu> build(List<Menu> rootMenu){
                //2.遍历菜单
                rootMenu.forEach(menu -> {
                    System.out.println(menu.toString());
                });

        //3.创建一个专门用来存放一级菜单的集合
        List<Menu> menuList = new ArrayList<>();
        //4.把menu的id为0的数据都存进一级菜单
        for (Menu menu: rootMenu
        ) {
            if (menu.getParentId()==0L){
                menuList.add(menu);
            }
        }
        //5.为一级菜单设置子菜单
        for (Menu menu:menuList
        ) {
            menu.setChildMenus(getChild(menu.getId(),rootMenu));
        }
        Collections.sort(menuList,Menu.order());

        return menuList;
    }

    private static List<Menu> getChild(Long id, List<Menu> rootMenu) {
        List<Menu> menuChild = new ArrayList<>();
        //该菜单的父级id必须是id不能是按钮
        for (Menu menu:rootMenu
        ) {
            if (menu.getParentId().equals(id)&& menu.getType().equals("0")){
                menuChild.add(menu);
            }
        }
        //设置二级菜单以上的菜单
        for (Menu menu:menuChild
        ) {
            menu.setChildMenus(getChild(menu.getId(),rootMenu));
        } 

        //判断递归结束的条件
        if (menuChild.size()==0){
            return null;
        }

        return  menuChild;
    }
}
